
import _ from 'lodash'
import * as userProxy from '../../proxys/user'
import { CustomError, CODE, ErrorInfo } from '../../error'
import { minLicenseLevel } from '../../config/router'
import rules from '../../config/rules'
import { proto, teams } from '../../config'

export const login = (data, req, res, next) => {
  return userProxy.login(data)
    .then( auth => {
      let MinLicenseLevel = minLicenseLevel[req.baseUrl] || 0
      if (auth.group.level < MinLicenseLevel) {
        throw ErrorInfo(CODE.ERROR_LICENSE_PGAE)
      }
      if (auth.freeze) {
        throw ErrorInfo(CODE.ERROR_ACCOUNT_FREEZE)
      }
      let info = { auth, rules, teams }
      if (_.has(proto, 'rtsps')) {
        info = { ...info, rtsp_keys: _.keys(proto.rtsps) }
      }
      return res.api(info) 
    })
    .catch(CustomError, err =>  res.api(null, err.code) )
    .catch( err => next(err) )
}

export const accesstoken = (auth, req, res, next) => {
  let info = { auth, rules, teams }
  if (_.has(proto, 'rtsps')) {
    info = { ...info, rtsp_keys: _.keys(proto.rtsps) }
  }
  return res.api(info)
}